/*
 * Author: vyouzhi <vyouzhi@163.com>
 * http://www.xda.cn
 *
 * File: main.c
 * Create Date: 2011-09-26 15:55:38
 *
 */
#include <error.h>
#include <stdbool.h>

#include "log_lib.h"
#include "thread_lib.h"
#include "conf_lib.h"
#include "action_lib.h"
#include "daemon_lib.h"
#include "signal_lib.h"
#include "status_lib.h"

int main(int argc, char* argv[]){
	int listen_fd, unix_sock;
	int h, thread_num;
	char *c, pid_file[500];
	bool do_daemonize = false;


	set_signal();

	if(argc < 2){
		printf("%s --help\n", argv[0]);
		exit(-1);
	}
	while((h = getopt(argc, argv, "c:d")) != -1){
		switch(h){
			case 'c':
				c = optarg;
				break;
			case 'd':
				do_daemonize = true;
				break;
			default:
				printf("%s --help\n", argv[0]);
				exit(-1);
		}
	}

	conf_init(c);

    Get_FieldName();
    status_init_all();

	d_log("ver:0.5.1 start ...");

	if(do_daemonize || atoi(conf_get("do_daemonize")) == 1){
		daemon_init(argv[0], 0);	
		if(strlen(conf_get("pid_file")) > 0)strcpy(pid_file, conf_get("pid_file"));
		else strcpy(pid_file, "/var/run/sqlproxy.pid");

		save_pid(getpid(), pid_file);
	}

	main_base = event_init();

	thread_num = atoi(conf_get("thread_num"));
	if(thread_num < 1) exit(-1);
	thread_init(thread_num);

	unix_sock = atoi(conf_get("unix_sock"));
	if(0 == unix_sock)
		listen_fd = Socket_Init();
	else
		listen_fd = server_socket_unix(); 

	if (listen_fd < 0){
		perror( "listen failed");
		exit(-1);
	}

	conn_new(listen_fd, main_base);

	event_base_loop(main_base, 0);

    return 0;
}
/* vim: set ts=4 sw=4: */

